package mymiddleware

import (
	"gf-xb-api/cwt/result"
	"net/http"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
)

// MiddlewareHandlerResponse 返回值设置
func MiddlewareHandlerResponse(r *ghttp.Request) {
	r.Middleware.Next()

	// There's custom buffer content, it then exits current handler.
	if r.Response.BufferLength() > 0 {
		return
	}

	var (
		msg        string
		err        = r.GetError()
		res        = r.GetHandlerResponse()
		code       = gerror.Code(err)
		resultType = result.CodeOK
	)
	if err != nil {
		if code == gcode.CodeNil {
			code = gcode.CodeInternalError
		}

		resultType = result.CodeInternalError
		msg = err.Error()
	} else {
		if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
			msg = http.StatusText(r.Response.Status)
			switch r.Response.Status {
			case http.StatusNotFound:
				code = gcode.CodeNotFound
				resultType = result.CodeInternalError
			case http.StatusForbidden:
				code = gcode.CodeNotAuthorized
				resultType = result.CodeNotAuthorized
			default:
				code = gcode.CodeUnknown
				resultType = result.CodeInternalError
			}
			// It creates error as it can be retrieved by other middlewares.
			err = gerror.NewCode(code, msg)
			r.SetError(err)
		} else {
			code = gcode.CodeOK
			resultType = result.CodeOK
		}
	}
	// 删除掉或注释掉
	/*r.Response.WriteJson(result.ResultRes{
		Code:    code.Code(),
		Message: msg,
		Data:    res,
	})*/

	/*// code正常，直接写回结果到客户端
	if code == gcode.CodeOK {
		r.Response.WriteJson(res)
	} else {
		// 非正常，重新组装结果数据，把系统相关code和错误信息一并返回客户端
		r.Response.WriteJson(result.OperationResultRes{
			ResultType: resultType.ResultType(),
			Message:    msg,
			Data:       nil,
		})
	}*/

	succeeded := resultType == result.CodeOK

	r.Response.WriteJson(result.OperationResultRes{
		ResultType: resultType.ResultType(),
		Message:    msg,
		Data:       res,
		Succeeded:  succeeded,
		Error:      !succeeded,
	})
}
